package com.ruoyi.web.controller.web3j;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web3jutil.Web3jUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * 区块链账户管理控制器
 * 
 * @author ruoyi
 */
@Api(tags = "区块链账户管理")
@RestController
@RequestMapping("/web3j/account")
public class Web3jAccountController {

    /**
     * 创建新的以太坊账户
     * 
     * @return 新创建的账户信息
     */
    @ApiOperation(value = "创建新的以太坊账户", notes = "创建一个新的以太坊账户并返回地址和私钥")
    @GetMapping("/create")
    public AjaxResult createAccount() {
        try {
            String[] accountInfo = Web3jUtil.createNewAddress();
            return AjaxResult.success("创建账户成功", new AccountInfo(accountInfo[0], accountInfo[1]));
        } catch (Exception e) {
            return AjaxResult.error("创建账户失败: " + e.getMessage());
        }
    }

    /**
     * 获取随机主账户
     * 
     * @return 随机主账户信息
     */
    @ApiOperation(value = "获取随机主账户", notes = "从主账户池中随机获取一个账户信息")
    @GetMapping("/random")
    public AjaxResult getRandomMainAccount() {
        String[] accountInfo = Web3jUtil.getRandomMainAddress();
        if (accountInfo == null) {
            return AjaxResult.error("获取随机主账户失败，主账户池为空");
        }
        return AjaxResult.success("获取随机主账户成功", new AccountInfo(accountInfo[0], accountInfo[1]));
    }

    /**
     * 获取账户余额
     * 
     * @param address 账户地址
     * @return 账户余额信息
     */
    @ApiOperation(value = "获取账户余额", notes = "根据账户地址查询其ETH余额")
    @GetMapping("/balance/{address}")
    public AjaxResult getAccountBalance(@PathVariable("address") String address) {
        try {
            BigDecimal balance = Web3jUtil.getEtherBalance(address);
            return AjaxResult.success("获取余额成功", balance);
        } catch (IOException e) {
            return AjaxResult.error("获取余额失败: " + e.getMessage());
        }
    }

    /**
     * 账户信息内部类
     */
    static class AccountInfo {
        private String address;
        private String privateKey;

        public AccountInfo(String address, String privateKey) {
            this.address = address;
            this.privateKey = privateKey;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public String getPrivateKey() {
            return privateKey;
        }

        public void setPrivateKey(String privateKey) {
            this.privateKey = privateKey;
        }
    }
}